package com.kikt.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by kikt on 2016/1/2.
 * 核心类
 */
public class Client {

    private static Client client;
    private static String host;
    private static int port;
    private SendThread sendThread;
    private ReceiveThread receiveThread;
    private Socket socket;
    private boolean isRun = true;
    private InetSocketAddress endpoint;

    private Client() {
        init();
    }

    /**
     * 初始化方法
     */
    private void init() {
        //初始化线程
        sendThread = new SendThread();
        receiveThread = new ReceiveThread();

        //初始化socket
        socket = new Socket();
    }

    public static Client getInstance(String host, int port) {
        Client.host = host;
        Client.port = port;
        if (client == null) {
            client = new Client();
        }
        return client;
    }

    public void connect() {
        try {
            isRun = true;
            endpoint = new InetSocketAddress(host, port);
            socket.connect(endpoint);
            receiveThread.start();
            sendThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void reconnect() {
        try {
            socket.connect(endpoint);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private MsgListener listener;

    public void setListener(MsgListener listener) {
        this.listener = listener;
    }

    public class ReceiveThread extends Thread {
        @Override
        public void run() {
            BufferedReader reader=null;
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (isRun) {
                try {
                    assert reader != null;
                    String line=reader.readLine();
                    byte[] bytes = line.getBytes();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class SendThread extends Thread {
        @Override
        public void run() {
            while (isRun) {

            }
        }
    }


}
